import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import systemRouter from "@/router/systemRouter";
import pinia from "@/store";
import { useRouterMenuStore } from "@/store/modules/routerMenusStore";
import { IRouteMenu } from "@/models/IRouterMenu";
import NProgress from 'nprogress'
import "nprogress/nprogress.css";
import { ElNotification } from "element-plus";
import { useDefaultConfig } from "@/config/defaultConfig";
import { checkTokenExp } from "@/utils";
import { useHelper } from '@/store/modules/storeHelper'
import layout from '@/layout/index.vue'
import login from '@/views/login/index.vue'
import home from '@/views/home/index.vue'
const config = useDefaultConfig()
//系统特殊路由
const routes_404 = {
	path: "/:pathMatch(.*)*",
	hidden: true,
	component: () => import('@/layout/other/404.vue'),
}
const router = createRouter({
	history: createWebHashHistory(),
	routes: [
		{
			name: "layout",
			path: "/",
			component: layout,
			redirect: config.DASHBOARD_URL || '/dashboard',
			children: [
				{
					name: "dashboard",
					path: "/dashboard",
					meta: {
						title: "控制台",
						icon: 'Menu',
						affix: true,
						type: 'menu',
						parentPath: '/home'
					},
					component: home
				}
			]
		},
		{
			path: "/login",
			component: login,
			meta: {
				title: "登录"
			}
		}
	]
})
//判断是否已加载过动态/静态路由
var isGetRouter = false;
const routerStore = useRouterMenuStore(pinia)
const defaultLogin = '/login'
router.beforeEach(async (to, from, next) => {
	NProgress.start()
	document.title = to.meta.title ? `${to.meta.title} - ${config.APP_NAME}` : `${config.APP_NAME}`
	if (checkTokenExp()) {
		localStorage.clear()
		useHelper.resetStore()
		if (to.path === defaultLogin) {
			next()
		} else {
			ElNotification.error({
				title: '认证失效提示',
				message: '身份认证时间已过期，系统已自动退出，请重新登陆！',
				type: 'error'
			})
			next(defaultLogin)
		}
	} else {
		const routeLength = router.getRoutes().length
		//整页路由处理
		if (to.meta.fullpage) {
			to.matched = [to.matched[to.matched.length - 1]]
		}
		//加载动态/静态路由
		if (!isGetRouter) {
			let apiMenu = routerStore.getMenus as IRouteMenu[]
			let menu = [...apiMenu]
			var menuRouter = filterAsyncRouter(menu)
			menuRouter = flatAsyncRoutes(menuRouter)
			routerStore.setPlatMenus(menuRouter)
			menuRouter.forEach((item: any) => {
				if (!router.hasRoute(item.name))
					router.addRoute("layout", item)
			})
			router.addRoute(routes_404)
			isGetRouter = true;
		}
		if (routeLength === 3) {
			next({ path: config.DASHBOARD_URL, replace: true });
		} else {
			next();
		}
	}

});

router.afterEach((to, from) => {
	// afterEach(to)
	NProgress.done()
});

router.onError((error) => {
	NProgress.done();
	ElNotification.error({
		title: '路由错误',
		message: error.message
	});
});
const modules = import.meta.glob('../views/**/*.vue')
function filterAsyncRouter(routerMap: Array<IRouteMenu>) {
	const accessedRouters: any = []
	routerMap.forEach((item: any) => {
		item.meta = item.meta ? item.meta : {};
		//处理外部链接特殊路由
		if (item.meta.type == 'iframe') {
			item.meta.url = item.path;
			item.path = `/i/${item.name}`;
		}
		//MAP转路由对象
		var route = {
			path: item.path,
			name: item.name,
			meta: item.meta,
			redirect: item.redirect,
			children: item.children ? filterAsyncRouter(item.children) : [],
			component: loadComponent(item.component)
		}
		accessedRouters.push(route)
	})
	return accessedRouters
}
function loadComponent(component: string) {
	if (component) {
		let newComponent = modules[component]
		return newComponent
	} else {
		return () => import(`@/layout/other/empty.vue`)
	}
}
function flatAsyncRoutes(routes: Array<IRouteMenu>) {
	let res: Array<IRouteMenu> = []
	routes.forEach((route: IRouteMenu) => {
		if (route.children) {
			res.push(route)
			res.push(...flatAsyncRoutes(route.children))
		} else {
			res.push(route)
		}
	})
	return res
}
export default router